<?php

class DistributionController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
//	public $layout='//layouts/column2';
        public $layout = '//layouts/eastsouthwest';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','choosedate','groupupdate'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','generate','generateform'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Distribution;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Distribution']))
		{
			$model->attributes=$_POST['Distribution'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->iddistribution));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Distribution']))
		{
			$model->attributes=$_POST['Distribution'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->iddistribution));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Distribution');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{

                if(isset(Yii::app()->session['distributiondate'])){
                    $model=new Distribution('search');
                    $model->unsetAttributes();  // clear any default values
                    if(isset($_GET['Distribution']))
                            $model->attributes=$_GET['Distribution'];
                }
                else{
                    $model=new Distribution('search');
//                    $model->unsetAttributes();  // clear any default values
//                    if(isset($_GET['Distribution']))
//                            $model->attributes=$_GET['Distribution'];                    
                }

		$this->render('admin',array(
			'model'=>$model,
		));
	}

        public function actionGenerate(){
            $distributiondate =  date('Y-m-d', CDateTimeParser::parse($_REQUEST['distributiondate'], 'dd/MM/yyyy'));
            $idfinancialyear = Yii::app()->session['idfinancialyear'];

            $sql = "SELECT * FROM {{distribution}} WHERE distributiondate='$distributiondate'";
            $connection=Yii::app()->db;
            $rowCount=$connection->createCommand($sql)->execute();
            if(isset($rowCount) && $rowCount>0){                
                Yii::app()->user->setFlash('distribution',"Oops! Can't generate 'Distribution' twice for Date.");
            }
            else{
                Yii::app()->user->setFlash('distribution',"'Distribution' generated successfuly for current date.");
                $sql = "INSERT INTO {{demand}} (idfinancialyear, idstockitem, demandquantity, idsociety) " .
                "SELECT $idfinancialyear as idfinancialyear, si.idstockitem, 0 as demandquantity, s.idsociety FROM {{society}} s, {{stockitem}} si ".
                "order by s.idsociety";
                $sql = "INSERT INTO {{distribution}} (idfinancialyear, distributiondate, idsociety, idstockitem, distributionquantity, availabilityquantity) " .
                "SELECT idfinancialyear, '$distributiondate' as distributiondate, idsociety, idstockitem, 0 as distributionquantity, 0 as availabilityquantity " .
                "FROM {{demand}} WHERE idfinancialyear=$idfinancialyear ORDER BY idsociety, idstockitem";
                $connection=Yii::app()->db;
                $connection->createCommand($sql)->execute();                
            }
            $this->render('generateform',array());
        }
        
        public function actionGenerateform(){            
		$this->render('generateform',array(
//			'model'=>$model,
		));
        }
        
        public function actionChoosedate(){   
            if($_REQUEST['distributiondate']){
                $distributiondate =  date('Y-m-d', CDateTimeParser::parse($_REQUEST['distributiondate'], 'dd/MM/yyyy'));
                Yii::app()->session['distributiondate'] = $distributiondate;
            }
            $this->redirect(array('distribution/admin'));
        }
        
        public function actionGroupupdate(){
            $distributionquantity = $_REQUEST['distributionquantity'];
            $availabilityquantity = $_REQUEST['availabilityquantity'];
            foreach($distributionquantity as $key=>$value){
                $sql = "Update {{distribution}} set distributionquantity=$value WHERE iddistribution=$key";
                $connection=Yii::app()->db;
                $connection->createCommand($sql)->execute();                
            }
            foreach($availabilityquantity as $key=>$value){
                $sql = "Update {{distribution}} set availabilityquantity=$value WHERE iddistribution=$key";
                $connection=Yii::app()->db;
                $connection->createCommand($sql)->execute();                
            }

            $this->redirect(array('distribution/admin'));
        }
        
        
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Distribution::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='distribution-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
